#define BLINKER_WIFI  // 启用Blinker的WiFi功能
#include <Blinker.h>  // 引入Blinker库
#include <Servo.h>    // 引入Servo库控制舵机
#include <EEPROM.h>   // 用于存储Wi-Fi配置

// 创建舵机对象
Servo myServo;

// 引脚定义
const int servoPin = 5;

// 舵机参数
const int ANGLE_REST = 10;
const int ANGLE_PRESS = 90;
const unsigned long PRESS_DELAY_MS = 500;

// 防重复点击设置
const unsigned long COOLDOWN_PERIOD = 5000;
unsigned long lastPressTime = 0;
bool isCoolingDown = false;

// Wi-Fi配置存储结构
struct WiFiConfig {
  char ssid[32];
  char password[64];
  char auth[32];
  bool configured;
};

WiFiConfig wifiConfig;

// 网页服务器相关
#include <ESP8266WebServer.h>
ESP8266WebServer server(80);

// 配网状态
bool isConfigMode = false;
unsigned long configStartTime = 0;
const unsigned long CONFIG_TIMEOUT = 300000; // 5分钟配网超时

// WiFi扫描相关
struct WiFiNetwork {
  String ssid;
  int rssi;
  int encryption;
};
std::vector<WiFiNetwork> wifiNetworks;
unsigned long lastScanTime = 0;
const unsigned long SCAN_INTERVAL = 30000; // 30秒扫描一次

// Blinker组件
BlinkerButton Button1("start-computer");

// 保存配置到EEPROM
void saveConfig() {
  EEPROM.begin(512);
  EEPROM.put(0, wifiConfig);
  EEPROM.commit();
  EEPROM.end();
  BLINKER_LOG("配置已保存到EEPROM");
}

// 从EEPROM加载配置
void loadConfig() {
  EEPROM.begin(512);
  EEPROM.get(0, wifiConfig);
  EEPROM.end();
  
  // 检查配置是否有效
  if (!wifiConfig.configured || strlen(wifiConfig.ssid) == 0) {
    BLINKER_LOG("未找到有效配置，进入配网模式");
    // 清空配置
    memset(&wifiConfig, 0, sizeof(wifiConfig));
    startConfigMode();
  }
}

// WiFi扫描函数
void scanWiFiNetworks() {
  BLINKER_LOG("正在扫描WiFi网络...");
  wifiNetworks.clear();
  
  int networkCount = WiFi.scanNetworks();
  
  if (networkCount == 0) {
    BLINKER_LOG("未发现WiFi网络");
    return;
  }

  BLINKER_LOG("发现 ", networkCount, " 个WiFi网络");
  
  // 存储扫描结果，去重并按信号强度排序
  for (int i = 0; i < networkCount; i++) {
    String ssid = WiFi.SSID(i);
    if (ssid.length() > 0) { // 过滤掉隐藏网络
      bool exists = false;
      // 检查是否已存在（去重）
      for (auto& network : wifiNetworks) {
        if (network.ssid == ssid) {
          // 如果信号更强，则更新
          if (WiFi.RSSI(i) > network.rssi) {
            network.rssi = WiFi.RSSI(i);
            network.encryption = WiFi.encryptionType(i);
          }
          exists = true;
          break;
        }
      }
      
      if (!exists) {
        WiFiNetwork network;
        network.ssid = ssid;
        network.rssi = WiFi.RSSI(i);
        network.encryption = WiFi.encryptionType(i);
        wifiNetworks.push_back(network);
      }
    }
  }
  
  // 按信号强度排序（从强到弱）
  std::sort(wifiNetworks.begin(), wifiNetworks.end(), [](const WiFiNetwork &a, const WiFiNetwork &b) {
    return a.rssi > b.rssi;
  });
  
  BLINKER_LOG("WiFi扫描完成，找到 ", wifiNetworks.size(), " 个有效网络");
  lastScanTime = millis();
}

// 获取信号强度描述
String getSignalStrength(int rssi) {
  if (rssi > -30) return "优秀";
  else if (rssi > -50) return "良好"; 
  else if (rssi > -70) return "一般";
  else return "较弱";
}

// 获取加密类型描述
String getEncryptionType(int encType) {
  switch (encType) {
    case ENC_TYPE_NONE: return "开放";
    case ENC_TYPE_WEP: return "WEP";
    case ENC_TYPE_TKIP: return "WPA/PSK";
    case ENC_TYPE_CCMP: return "WPA2/PSK";
    case ENC_TYPE_AUTO: return "WPA/WPA2/PSK";
    default: return "未知";
  }
}

// 启动配网模式
void startConfigMode() {
  isConfigMode = true;
  configStartTime = millis();
  BLINKER_LOG("启动配网模式...");
  
  // 先断开现有连接
  WiFi.disconnect();
  delay(100);
  
  // 启动AP模式，设置固定IP
  WiFi.mode(WIFI_AP);
  delay(100);
  
  // 配置AP的IP地址
  IPAddress local_IP(192, 168, 4, 1);
  IPAddress gateway(192, 168, 4, 1);
  IPAddress subnet(255, 255, 255, 0);
  
  WiFi.softAPConfig(local_IP, gateway, subnet);
  delay(100);
  
  bool apStarted = WiFi.softAP("ESP8266-Remote-Power", "12345678");
  delay(1000); // 等待AP完全启动
  
  if (apStarted) {
    IPAddress apIP = WiFi.softAPIP();
    BLINKER_LOG("配网模式已启动");
    BLINKER_LOG("AP名称: ESP8266-Remote-Power");
    BLINKER_LOG("AP密码: 12345678");
    BLINKER_LOG("配置页面地址: http://", apIP.toString());
    BLINKER_LOG("请连接到WiFi后访问上述地址进行配置");
    
    // 初始WiFi扫描
    scanWiFiNetworks();
  } else {
    BLINKER_LOG("AP启动失败，将重启设备");
    delay(2000);
    ESP.restart();
  }
  
  // 设置网页路由
  server.on("/", HTTP_GET, []() {
    // 检查是否需要重新扫描
    if (millis() - lastScanTime > SCAN_INTERVAL) {
      scanWiFiNetworks();
    }
    
    String html = "<!DOCTYPE html><html><head>";
    html += "<meta charset='utf-8'>";
    html += "<meta name='viewport' content='width=device-width, initial-scale=1.0'>";
    html += "<title>ESP8266 远程开机配置</title>";
    html += "<style>";
    
    // 全局样式和色彩变量
    html += ":root {";
    html += "  --primary-color: #4A90E2;";
    html += "  --primary-hover: #357ABD;";
    html += "  --success-color: #7ED321;";
    html += "  --success-hover: #5CB02E;";
    html += "  --warning-color: #F5A623;";
    html += "  --danger-color: #D0021B;";
    html += "  --text-primary: #2C3E50;";
    html += "  --text-secondary: #7F8C8D;";
    html += "  --bg-primary: #FFFFFF;";
    html += "  --bg-secondary: #F8F9FA;";
    html += "  --border-color: #E1E5E9;";
    html += "  --shadow-light: 0 2px 8px rgba(0,0,0,0.1);";
    html += "  --shadow-medium: 0 4px 16px rgba(0,0,0,0.15);";
    html += "}";
    
    // 基础样式
    html += "* { box-sizing: border-box; }";
    html += "body {";
    html += "  font-family: 'SF Pro Display', 'Microsoft YaHei', 'PingFang SC', sans-serif;";
    html += "  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);";
    html += "  margin: 0;";
    html += "  padding: 20px;";
    html += "  min-height: 100vh;";
    html += "  color: var(--text-primary);";
    html += "}";
    
    // 容器样式
    html += ".container {";
    html += "  max-width: 480px;";
    html += "  margin: 0 auto;";
    html += "  background: var(--bg-primary);";
    html += "  border-radius: 16px;";
    html += "  box-shadow: var(--shadow-medium);";
    html += "  overflow: hidden;";
    html += "}";
    
    // 头部样式
    html += ".header {";
    html += "  background: linear-gradient(135deg, var(--primary-color) 0%, #667eea 100%);";
    html += "  padding: 30px 20px;";
    html += "  text-align: center;";
    html += "  color: white;";
    html += "}";
    html += ".header h1 {";
    html += "  margin: 0;";
    html += "  font-size: 24px;";
    html += "  font-weight: 600;";
    html += "  letter-spacing: -0.5px;";
    html += "}";
    html += ".header .subtitle {";
    html += "  margin-top: 8px;";
    html += "  opacity: 0.9;";
    html += "  font-size: 14px;";
    html += "}";
    
    // 内容区域
    html += ".content {";
    html += "  padding: 25px;";
    html += "}";
    
    // 信息提示框
    html += ".info-box {";
    html += "  background: linear-gradient(135deg, #E3F2FD 0%, #F3E5F5 100%);";
    html += "  border: 1px solid #BBDEFB;";
    html += "  border-radius: 12px;";
    html += "  padding: 16px;";
    html += "  margin-bottom: 24px;";
    html += "  display: flex;";
    html += "  align-items: center;";
    html += "}";
    html += ".info-box .icon {";
    html += "  font-size: 20px;";
    html += "  margin-right: 12px;";
    html += "}";
    html += ".info-box .text {";
    html += "  color: var(--text-primary);";
    html += "  font-size: 14px;";
    html += "  line-height: 1.4;";
    html += "}";
    
    // 按钮样式
    html += ".btn {";
    html += "  display: inline-block;";
    html += "  padding: 12px 24px;";
    html += "  border: none;";
    html += "  border-radius: 10px;";
    html += "  font-size: 14px;";
    html += "  font-weight: 500;";
    html += "  cursor: pointer;";
    html += "  transition: all 0.2s ease;";
    html += "  text-decoration: none;";
    html += "  width: 100%;";
    html += "}";
    html += ".btn-primary {";
    html += "  background: linear-gradient(135deg, var(--primary-color) 0%, #667eea 100%);";
    html += "  color: white;";
    html += "}";
    html += ".btn-primary:hover {";
    html += "  transform: translateY(-2px);";
    html += "  box-shadow: var(--shadow-medium);";
    html += "}";
    html += ".btn-success {";
    html += "  background: linear-gradient(135deg, var(--success-color) 0%, #4CAF50 100%);";
    html += "  color: white;";
    html += "  margin-bottom: 20px;";
    html += "}";
    html += ".btn-success:hover {";
    html += "  transform: translateY(-2px);";
    html += "  box-shadow: var(--shadow-medium);";
    html += "}";
    
    // WiFi列表样式
    html += ".wifi-section {";
    html += "  margin-bottom: 24px;";
    html += "}";
    html += ".wifi-list {";
    html += "  border: 1px solid var(--border-color);";
    html += "  border-radius: 12px;";
    html += "  max-height: 280px;";
    html += "  overflow-y: auto;";
    html += "  margin: 16px 0;";
    html += "  background: var(--bg-secondary);";
    html += "}";
    html += ".wifi-item {";
    html += "  padding: 16px;";
    html += "  border-bottom: 1px solid var(--border-color);";
    html += "  cursor: pointer;";
    html += "  display: flex;";
    html += "  justify-content: space-between;";
    html += "  align-items: center;";
    html += "  transition: all 0.2s ease;";
    html += "  background: white;";
    html += "}";
    html += ".wifi-item:last-child { border-bottom: none; }";
    html += ".wifi-item:hover {";
    html += "  background: var(--bg-secondary);";
    html += "  transform: translateX(4px);";
    html += "}";
    html += ".wifi-item.selected {";
    html += "  background: linear-gradient(135deg, #E3F2FD 0%, #F3E5F5 100%);";
    html += "  border-left: 4px solid var(--primary-color);";
    html += "  transform: translateX(0);";
    html += "}";
    html += ".wifi-info {";
    html += "  display: flex;";
    html += "  flex-direction: column;";
    html += "  flex: 1;";
    html += "}";
    html += ".wifi-ssid {";
    html += "  font-weight: 600;";
    html += "  font-size: 16px;";
    html += "  margin-bottom: 4px;";
    html += "  color: var(--text-primary);";
    html += "}";
    html += ".wifi-details {";
    html += "  font-size: 12px;";
    html += "  color: var(--text-secondary);";
    html += "  display: flex;";
    html += "  align-items: center;";
    html += "  gap: 8px;";
    html += "}";
    html += ".signal-strength {";
    html += "  display: inline-flex;";
    html += "  align-items: center;";
    html += "  font-size: 18px;";
    html += "}";
    
    // 表单样式
    html += ".form-group {";
    html += "  margin-bottom: 20px;";
    html += "}";
    html += ".form-label {";
    html += "  display: block;";
    html += "  margin-bottom: 8px;";
    html += "  font-weight: 500;";
    html += "  color: var(--text-primary);";
    html += "  font-size: 14px;";
    html += "}";
    html += ".form-input {";
    html += "  width: 100%;";
    html += "  padding: 14px 16px;";
    html += "  border: 1px solid var(--border-color);";
    html += "  border-radius: 10px;";
    html += "  font-size: 16px;";
    html += "  transition: all 0.2s ease;";
    html += "  background: white;";
    html += "}";
    html += ".form-input:focus {";
    html += "  outline: none;";
    html += "  border-color: var(--primary-color);";
    html += "  box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1);";
    html += "}";
    html += ".form-input::placeholder {";
    html += "  color: var(--text-secondary);";
    html += "}";
    
    // 手动输入切换
    html += ".manual-toggle {";
    html += "  color: var(--primary-color);";
    html += "  cursor: pointer;";
    html += "  font-size: 14px;";
    html += "  text-align: center;";
    html += "  padding: 12px;";
    html += "  border: 1px dashed var(--border-color);";
    html += "  border-radius: 8px;";
    html += "  transition: all 0.2s ease;";
    html += "  margin: 16px 0;";
    html += "}";
    html += ".manual-toggle:hover {";
    html += "  background: var(--bg-secondary);";
    html += "  border-color: var(--primary-color);";
    html += "}";
    html += "#manual-input {";
    html += "  display: none;";
    html += "}";
    
    // 底部信息
    html += ".footer-info {";
    html += "  text-align: center;";
    html += "  font-size: 12px;";
    html += "  color: var(--text-secondary);";
    html += "  margin-top: 24px;";
    html += "  padding-top: 16px;";
    html += "  border-top: 1px solid var(--border-color);";
    html += "  line-height: 1.5;";
    html += "}";
    
    // 空状态
    html += ".empty-state {";
    html += "  padding: 40px 20px;";
    html += "  text-align: center;";
    html += "  color: var(--text-secondary);";
    html += "}";
    html += ".empty-state .icon {";
    html += "  font-size: 48px;";
    html += "  margin-bottom: 16px;";
    html += "  opacity: 0.5;";
    html += "}";
    
    // 响应式
    html += "@media (max-width: 480px) {";
    html += "  body { padding: 10px; }";
    html += "  .header { padding: 20px 15px; }";
    html += "  .header h1 { font-size: 20px; }";
    html += "  .content { padding: 20px; }";
    html += "}";
    
    html += "</style>";
    html += "<script>";
    html += "let selectedSSID = '';";
    html += "function selectWiFi(ssid, encrypted) {";
    html += "  selectedSSID = ssid;";
    html += "  document.querySelectorAll('.wifi-item').forEach(item => item.classList.remove('selected'));";
    html += "  event.currentTarget.classList.add('selected');";
    html += "  document.getElementById('ssid').value = ssid;";
    html += "  document.getElementById('password').style.display = encrypted ? 'block' : 'none';";
    html += "  document.getElementById('password-group').style.display = encrypted ? 'block' : 'none';";
    html += "  document.getElementById('password').required = encrypted;";
    html += "  document.getElementById('manual-input').style.display = 'none';";
    html += "}";
    html += "function toggleManual() {";
    html += "  const manual = document.getElementById('manual-input');";
    html += "  if (manual.style.display === 'none') {";
    html += "    manual.style.display = 'block';";
    html += "    document.querySelectorAll('.wifi-item').forEach(item => item.classList.remove('selected'));";
    html += "    document.getElementById('ssid').value = '';";
    html += "    document.getElementById('password-group').style.display = 'block';";
    html += "    document.getElementById('password').required = true;";
    html += "  } else {";
    html += "    manual.style.display = 'none';";
    html += "  }";
    html += "}";
    html += "function refreshWiFi() {";
    html += "  const btn = document.getElementById('refresh-btn');";
    html += "  btn.innerHTML = '🔄 扫描中...';";
    html += "  btn.disabled = true;";
    html += "  setTimeout(() => location.reload(), 500);";
    html += "}";
    html += "</script>";
    html += "</head>";
    
    html += "<body>";
    html += "<div class='container'>";
    
    // 头部
    html += "<div class='header'>";
    html += "<h1>🖥️ 远程开机配置</h1>";
    html += "<div class='subtitle'>ESP8266 Remote Power Controller</div>";
    html += "</div>";
    
    // 内容区域
    html += "<div class='content'>";
    
    // 信息提示
    html += "<div class='info-box'>";
    html += "<div class='icon'>💡</div>";
    html += "<div class='text'>请选择您的WiFi网络并填写相关信息，配置完成后设备将自动重启</div>";
    html += "</div>";
    
    // WiFi扫描区域
    html += "<div class='wifi-section'>";
    html += "<button type='button' class='btn btn-success' id='refresh-btn' onclick='refreshWiFi()'>🔄 刷新WiFi列表</button>";
    
    html += "<div class='wifi-list'>";
    if (wifiNetworks.size() > 0) {
      for (const auto& network : wifiNetworks) {
        bool encrypted = (network.encryption != ENC_TYPE_NONE);
        String lockIcon = encrypted ? "🔒" : "📶";
        String signalIcon;
        if (network.rssi > -50) signalIcon = "📶";
        else if (network.rssi > -70) signalIcon = "📶";
        else signalIcon = "📶";
        
        html += "<div class='wifi-item' onclick='selectWiFi(\"" + network.ssid + "\", " + (encrypted ? "true" : "false") + ")'>";
        html += "<div class='wifi-info'>";
        html += "<div class='wifi-ssid'>" + lockIcon + " " + network.ssid + "</div>";
        html += "<div class='wifi-details'>";
        html += "<span>" + getSignalStrength(network.rssi) + "</span>";
        html += "<span>(" + String(network.rssi) + "dBm)</span>";
        html += "<span>" + getEncryptionType(network.encryption) + "</span>";
        html += "</div>";
        html += "</div>";
        html += "<div class='signal-strength'>" + signalIcon + "</div>";
        html += "</div>";
      }
    } else {
      html += "<div class='empty-state'>";
      html += "<div class='icon'>📡</div>";
      html += "<div>未发现WiFi网络<br>请点击刷新重试</div>";
      html += "</div>";
    }
    html += "</div>";
    html += "</div>";
    
    // 手动输入切换
    html += "<div class='manual-toggle' onclick='toggleManual()'>";
    html += "📝 手动输入WiFi信息";
    html += "</div>";
    
    // 配置表单
    html += "<form method='POST' action='/configure'>";
    html += "<input type='hidden' id='ssid' name='ssid' required>";
    
    html += "<div id='manual-input'>";
    html += "<div class='form-group'>";
    html += "<label class='form-label'>WiFi名称 (SSID)</label>";
    html += "<input type='text' class='form-input' name='manual-ssid' placeholder='请输入WiFi名称'>";
    html += "</div>";
    html += "</div>";
    
    html += "<div class='form-group' id='password-group' style='display:none;'>";
    html += "<label class='form-label'>WiFi密码</label>";
    html += "<input type='password' class='form-input' id='password' name='password' placeholder='请输入WiFi密码'>";
    html += "</div>";
    
    html += "<div class='form-group'>";
    html += "<label class='form-label'>Blinker密钥 (AuthKey)</label>";
    // 如果已有配置，则显示为默认值
    String authValue = (strlen(wifiConfig.auth) > 0) ? String(wifiConfig.auth) : "";
    html += "<input type='text' class='form-input' name='auth' placeholder='请输入Blinker密钥' value='" + authValue + "' required>";
    html += "</div>";
    
    html += "<button type='submit' class='btn btn-primary'>💾 保存配置并重启</button>";
    html += "</form>";
    
    // 底部信息
    html += "<div class='footer-info'>";
    html += "🕒 WiFi扫描时间: " + String((millis() - lastScanTime) / 1000) + "秒前<br>";
    html += "📱 请确保Blinker密钥正确，设备重启后即可使用APP控制";
    html += "</div>";
    
    html += "</div>"; // content
    html += "</div>"; // container
    html += "</body></html>";
    
    server.send(200, "text/html", html);
  });

  server.on("/configure", HTTP_POST, []() {
    String ssid = server.arg("ssid");
    String manualSsid = server.arg("manual-ssid");
    String password = server.arg("password");
    String auth = server.arg("auth");
    
    // 如果手动输入了SSID，则使用手动输入的
    if (manualSsid.length() > 0) {
      ssid = manualSsid;
    }
    
    if (ssid.length() > 0 && auth.length() > 0) {
      // 清空配置结构
      memset(&wifiConfig, 0, sizeof(wifiConfig));
      
      // 保存新配置
      ssid.toCharArray(wifiConfig.ssid, sizeof(wifiConfig.ssid));
      password.toCharArray(wifiConfig.password, sizeof(wifiConfig.password));
      auth.toCharArray(wifiConfig.auth, sizeof(wifiConfig.auth));
      wifiConfig.configured = true;
      
      saveConfig();
      
      String html = "<!DOCTYPE html><html><head><meta charset='utf-8'>";
      html += "<meta name='viewport' content='width=device-width, initial-scale=1.0'>";
      html += "<title>配置成功</title>";
      html += "<style>body{font-family:'Microsoft YaHei',Arial,sans-serif;max-width:400px;margin:50px auto;padding:20px;text-align:center;background:#f5f5f5;}";
      html += ".success{background:white;padding:40px;border-radius:10px;box-shadow:0 2px 10px rgba(0,0,0,0.1);}";
      html += "h2{color:#28a745;margin-bottom:20px;}";
      html += ".info{color:#666;margin-top:20px;}";
      html += "</style></head>";
      html += "<body><div class='success'>";
      html += "<h2>✓ 配置保存成功！</h2>";
      html += "<p>设备将在3秒后重启并尝试连接到指定WiFi</p>";
      html += "<div class='info'>WiFi: " + ssid + "</div>";
      html += "</div></body></html>";
      server.send(200, "text/html", html);
      
      BLINKER_LOG("收到新配置 - SSID: ", ssid);
      delay(3000);
      ESP.restart();
    } else {
      String html = "<!DOCTYPE html><html><head><meta charset='utf-8'><title>配置错误</title></head>";
      html += "<body><h2>配置错误</h2><p>请确保WiFi名称和Blinker密钥不为空</p>";
      html += "<a href='/'>返回配置页面</a></body></html>";
      server.send(400, "text/html", html);
    }
  });

  server.begin();
  BLINKER_LOG("Web服务器已启动");
}

// 尝试连接WiFi
bool connectWiFi() {
  if (strlen(wifiConfig.ssid) == 0) {
    BLINKER_LOG("WiFi SSID为空");
    return false;
  }

  BLINKER_LOG("正在连接WiFi: ", wifiConfig.ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifiConfig.ssid, wifiConfig.password);
  
  int attempts = 0;
  while (WiFi.status() != WL_CONNECTED && attempts < 30) {
    delay(500);
    Serial.print(".");
    attempts++;
  }
  Serial.println();
  
  if (WiFi.status() == WL_CONNECTED) {
    BLINKER_LOG("WiFi连接成功!");
    BLINKER_LOG("IP地址: ", WiFi.localIP().toString());
    BLINKER_LOG("信号强度: ", WiFi.RSSI(), " dBm");
    return true;
  } else {
    BLINKER_LOG("WiFi连接失败，状态码: ", WiFi.status());
    return false;
  }
}

// 按下Blinker APP按钮时执行的回调函数
void button1_callback(const String & state) {
    if (isConfigMode) {
        BLINKER_LOG("配网模式中，按钮功能暂不可用");
        return;
    }
    
    BLINKER_LOG("收到按钮状态: ", state);
    
    unsigned long currentTime = millis();
    
    if (isCoolingDown) {
        unsigned long remainingTime = COOLDOWN_PERIOD - (currentTime - lastPressTime);
        BLINKER_LOG("冷却中，请等待 ", remainingTime / 1000, " 秒后再试");
        
        Blinker.vibrate();
        Blinker.delay(100);
        Blinker.vibrate();
        return;
    }
    
    pressButton();
    lastPressTime = currentTime;
    isCoolingDown = true;
    BLINKER_LOG("按钮已按下，进入5秒冷却时间");
}

// 控制舵机执行按下动作的函数
void pressButton() {
    BLINKER_LOG("开始执行按钮按下动作...");
    myServo.attach(servoPin);
    delay(100);
    
    BLINKER_LOG("舵机转到按下位置");
    myServo.write(ANGLE_PRESS);
    delay(PRESS_DELAY_MS);
    
    BLINKER_LOG("舵机返回初始位置");
    myServo.write(ANGLE_REST);
    delay(500);
    
    myServo.detach();
    BLINKER_LOG("电源按钮按下动作已完成");
}

// 检查冷却状态
void checkCooldown() {
    if (isCoolingDown) {
        unsigned long currentTime = millis();
        if (currentTime - lastPressTime >= COOLDOWN_PERIOD) {
            isCoolingDown = false;
            BLINKER_LOG("冷却时间结束，可以再次使用");
        }
    }
}

void dataRead(const String & data) {
    BLINKER_LOG("Blinker 读取字符串: ", data);
}

void setup() {
    Serial.begin(115200);
    delay(1000);
    Serial.println();
    Serial.println("=== ESP8266远程开机系统启动 ===");
    
    BLINKER_DEBUG.stream(Serial);

    // 初始化EEPROM并加载配置
    loadConfig();

    // 初始化舵机到初始位置
    myServo.attach(servoPin);
    myServo.write(ANGLE_REST);
    delay(1000);
    myServo.detach();
    BLINKER_LOG("舵机初始化完成");

    if (!isConfigMode) {
        // 尝试连接WiFi
        if (connectWiFi()) {
            // WiFi连接成功，初始化Blinker
            BLINKER_LOG("正在初始化Blinker...");
            Blinker.begin(wifiConfig.auth, wifiConfig.ssid, wifiConfig.password);
            Button1.attach(button1_callback);
            Blinker.attachData(dataRead);
            BLINKER_LOG("设备初始化完成，等待指令...");
            BLINKER_LOG("可以使用Blinker APP进行远程控制了");
        } else {
            // WiFi连接失败，清除配置并进入配网模式
            BLINKER_LOG("WiFi连接失败，清除配置并进入配网模式");
            memset(&wifiConfig, 0, sizeof(wifiConfig));
            saveConfig();
            delay(1000);
            ESP.restart();
        }
    }
}

void loop() {
    if (isConfigMode) {
        // 配网模式下的处理
        server.handleClient();
        
        // 检查配网超时
        if (millis() - configStartTime > CONFIG_TIMEOUT) {
            BLINKER_LOG("配网超时，设备将重启");
            delay(1000);
            ESP.restart();
        }
        
        // 每30秒提醒一次配网信息
        static unsigned long lastReminder = 0;
        if (millis() - lastReminder > 30000) {
            IPAddress apIP = WiFi.softAPIP();
            BLINKER_LOG("配网提醒 - 请连接WiFi: ESP8266-Remote-Power, 访问: http://", apIP.toString());
            lastReminder = millis();
        }
        
        // 定期重新扫描WiFi（每30秒）
        if (millis() - lastScanTime > SCAN_INTERVAL) {
            scanWiFiNetworks();
        }
    } else {
        // 正常模式下的处理
        Blinker.run();
        checkCooldown();
        
        // 检查WiFi连接状态
        static unsigned long lastWiFiCheck = 0;
        if (millis() - lastWiFiCheck > 30000) { // 每30秒检查一次
            if (WiFi.status() != WL_CONNECTED) {
                BLINKER_LOG("WiFi连接丢失，尝试重连...");
                if (!connectWiFi()) {
                    BLINKER_LOG("WiFi重连失败，设备将重启");
                    delay(1000);
                    ESP.restart();
                }
            }
            lastWiFiCheck = millis();
        }
    }
}